//
//  UIImage+ZZ.swift
//  BuildingWeather
//
//  Created by 陈钟 on 2019/5/9.
//  Copyright © 2019 陈钟. All rights reserved.
//

import Foundation
import UIKit

public extension UIImage{

    /// 取图片 UIImage.init(named: name)
    static func named(name:String) -> UIImage?{
        return UIImage.init(named: name)
    }
    /// 取图片  named(name:String) -> UIImage?
    static func name(_ name:String) -> UIImage?{
        return self.named(name: name)
    }
    ///base64图片
    static func base64(base64:String) -> UIImage?{
        guard let imageData = Data.init(base64Encoded: base64, options: Data.Base64DecodingOptions.ignoreUnknownCharacters) else { return nil }
        let image = UIImage.init(data: imageData)
        return image
    }

    /// 使用颜色绘制一张图片 size:{1,1}
    ///
    /// - Parameter color: 将要绘制的图片颜色
    /// - Returns: 绘制完成的颜色图片
    static func image(color: UIColor) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context!.setFillColor(color.cgColor)
        context!.fill(rect)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img!
    }

    /// 使用颜色绘制一张图片 size:{1,1}
    ///
    /// - Parameter color: 将要绘制的图片颜色
    /// - Returns: 绘制完成的颜色图片
    static func imageWithColor(_ color: UIColor) -> UIImage{
        return self.image(color: color)
    }

    /// 使用颜色绘制一张图片
    ///
    /// - Parameters:
    ///   - color: 将要绘制的图片颜色
    ///   - size: 将要绘制的图片大小
    /// - Returns: 绘制完成的颜色图片
    static func image(color: UIColor, size: CGSize) -> UIImage? {
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context!.setFillColor(color.cgColor)
        context!.fill(rect)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }

    /// 截取View图片
    ///
    /// - Parameters:
    ///   - fromeView: view 窗体
    ///   - atFrame: 将要截图位置及大小
    /// - Returns: 截取的图片
    static func getSnapshot(_ fromeView:UIView?,atFrame:CGRect) -> UIImage? {
        if atFrame == CGRect.zero { return nil }
        guard let view = fromeView else { return nil }
        UIGraphicsBeginImageContextWithOptions(CGSize.init(width: atFrame.maxX, height: atFrame.maxY), false, 0)
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        var image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        if atFrame.x > 0 || atFrame.y > 0 { // 剪切图片
            let imageRef = image?.cgImage
            if let subImgRef = imageRef?.cropping(to: atFrame){
                image = UIImage.init(cgImage: subImgRef)
            }
        }
        return image
    }
    
    /// 修改图片的颜色
    func imageWithColor(_ color:UIColor) -> UIImage? {
        return self.imageWithTintColor(color, blendMode: CGBlendMode.destinationIn)
    }
    /// 修改图片的颜色
    func imageWithTintColor(_ color:UIColor,blendMode: CGBlendMode) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(self.size, false, 0)
        color.setFill()
        let bounds = CGRect.init(x: 0, y: 0, width: self.size.width, height: self.size.height)
        UIRectFill(bounds)
        self.draw(in: bounds, blendMode: blendMode, alpha: 1)
        if blendMode != CGBlendMode.destinationIn {
            self.draw(in: bounds, blendMode: CGBlendMode.destinationIn, alpha: 1)
        }
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
    /// 图片修改成圆角
    func roundImage(byRoundingCorners: UIRectCorner = UIRectCorner.allCorners, cornerRadi: CGFloat) -> UIImage? {
        return roundImage(byRoundingCorners: byRoundingCorners, cornerRadii: CGSize(width: cornerRadi, height: cornerRadi))
    }
    /// 图片修改成圆角
    func roundImage(byRoundingCorners: UIRectCorner = UIRectCorner.allCorners, cornerRadii: CGSize) -> UIImage? {
        
        let imageRect = CGRect(origin: CGPoint.zero, size: size)
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        defer {
            UIGraphicsEndImageContext()
        }
        let context = UIGraphicsGetCurrentContext()
        guard context != nil else {
            return nil
        }
        context?.setShouldAntialias(true)
        let bezierPath = UIBezierPath(roundedRect: imageRect,
                                      byRoundingCorners: byRoundingCorners,
                                      cornerRadii: cornerRadii)
        bezierPath.close()
        bezierPath.addClip()
        self.draw(in: imageRect)
        let reSizeImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return reSizeImage
    }
    
    /// 水平翻转图片
    ///
    /// - Returns: 水平翻转 UIImage
    func filpImage() -> UIImage {
        //翻转图片
        let flipImage = UIImage.init(cgImage: self.cgImage!, scale: self.scale, orientation: UIImage.Orientation.upMirrored)
        return flipImage
    }


    /// 向右旋转90° ⤼
    func byRotateRight90() -> UIImage{
        let image = UIImage(cgImage: self.cgImage!, scale: self.scale, orientation: UIImage.Orientation.right)
        return image
    }

    /// 旋转 翻折UIImage
    func orientation(_ orientation: UIImage.Orientation) -> UIImage{
        let image = UIImage(cgImage: self.cgImage!, scale: self.scale, orientation: orientation)
        return image
    }

    /**
     *  等比率缩放
     */
    func scaleImage(scaleSize:CGFloat) -> UIImage? {
        let reSize = CGSize.init(width: self.size.width * scaleSize, height: self.size.height * scaleSize)
        return self.reSizeImage(reSize: reSize)
    }
    
    /**
     *  重设图片大小
     */
    func reSizeImage(reSize:CGSize) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(reSize,false,UIScreen.main.scale)
        self.draw(in: CGRect.init(origin: CGPoint.zero, size: reSize))
        let reSizeImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return reSizeImage
    }
    /// 压缩图片数据-不压尺寸
    ///
    /// - Parameters:
    ///   - maxLength: 最大长度
    /// - Returns:
    func compressImageOnlength(maxLength: Int) -> Data? {
        guard let vData = self.jpegData(compressionQuality: 1) else { return nil }
        ZZLog("压缩前kb: \( Double((vData.count)/1024))")
        if vData.count < maxLength {
            return vData
        }
        var compress:CGFloat = 0.9
        guard var data = self.jpegData(compressionQuality: compress) else { return nil }
        while data.count > maxLength && compress > 0.01 {
            ZZLog("压缩比: \(compress)")
            compress -= 0.02
            data = self.jpegData(compressionQuality: compress)!
        }
        ZZLog("压缩后kb: \(Double((data.count)/1024))")
        return data
    }
    
    /// 压缩图片
    ///
    /// - Parameter maxLength: 图片压缩后最大字节
    /// - Returns: 压缩后的图片Data
    func compressImageMid(maxLength: Int) -> Data? {
        var compression: CGFloat = 1
        guard var data = self.jpegData(compressionQuality: 1) else { return nil }
        ZZLog("压缩前kb: \( Double((data.count) / 1024))")
        if data.count < maxLength {
            return data
        }
        print("压缩前kb", data.count / 1024, "KB")
        var max: CGFloat = 1
        var min: CGFloat = 0
        for _ in 0 ..< 6 {
            compression = (max + min) / 2
            data = self.jpegData(compressionQuality: compression)!
            if CGFloat(data.count) < CGFloat(maxLength) * 0.9 {
                min = compression
            } else if data.count > maxLength {
                max = compression
            } else {
                break
            }
        }
        
        print("压缩后kb", data.count / 1024, "KB")
        return data
    }
    
    /// 压缩图片
    ///
    /// - Parameter maxLength: 图片压缩后最大字节
    /// - Returns: 压缩后的图片
    func compressImage(maxLength: Int) -> UIImage? {
        if let data = self.compressImageMid(maxLength: maxLength){
            return UIImage.init(data: data)
        }
        return nil
    }
    /// 根据尺寸重新生成图片
    ///
    /// - Parameter size: 设置的大小
    /// - Returns: 新图
    func imageWithNewSize(size: CGSize) -> UIImage? {
        if self.size.height > size.height {
            
            let width = size.height / self.size.height * self.size.width
            
            let newImgSize = CGSize(width: width, height: size.height)
            
            UIGraphicsBeginImageContext(newImgSize)
            
            self.draw(in: CGRect(x: 0, y: 0, width: newImgSize.width, height: newImgSize.height))
            
            let theImage = UIGraphicsGetImageFromCurrentImageContext()
            
            UIGraphicsEndImageContext()
            
            guard let newImg = theImage else { return  nil}
            
            return newImg
        } else {
            
            let newImgSize = CGSize(width: size.width, height: size.height)
            
            UIGraphicsBeginImageContext(newImgSize)
            
            self.draw(in: CGRect(x: 0, y: 0, width: newImgSize.width, height: newImgSize.height))
            
            let theImage = UIGraphicsGetImageFromCurrentImageContext()
            
            UIGraphicsEndImageContext()
            
            guard let newImg = theImage else { return  nil}
            
            return newImg
        }
        
    }
    /// 给图片打上 文字
    func add(text:String,attributed:Dictionary<NSAttributedString.Key, Any>,scale:CGFloat) -> UIImage {
        
        //重新计算字体大小
        var newAtt = attributed
        let paragraphStyle = NSMutableParagraphStyle.init()
        paragraphStyle.lineSpacing = 10
        newAtt[.paragraphStyle] = paragraphStyle
        //字体
        var font = newAtt[.font] as? UIFont
        if font == nil{
            font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
            newAtt[.font] = font
        }
        let drawText = NSString.init(string: text)
        let drawTextSize = drawText.size(withAttributes: newAtt)
        //字号
        let fontSize = font!.pointSize
        //需要显示的文字宽度
        let textShowSize = min(self.size.width, self.size.height) * scale
        
        // 将要绘制的字号
        let willFontSize = fontSize * textShowSize / drawTextSize.width
        newAtt[.font] = UIFont.systemFont(ofSize: willFontSize)
        let newDrawTextSize = drawText.size(withAttributes: newAtt)
        
        
        UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)
        
        self.draw(in: CGRect.init(x: 0, y: 0, width: self.size.width, height: self.size.height))
        
//        for index in 0 ..< Int(self.size.height / newDrawTextSize.height) {
//            if index % 2 == 0 {
//                drawText.draw(at: CGPoint.init(x: 0, y: CGFloat(index) * newDrawTextSize.height), withAttributes: newAtt)
//            }
//        }
        
        drawText.draw(at: CGPoint.init(x: self.size.width * 0.01, y: self.size.height - newDrawTextSize.height - (self.size.height * 0.01)), withAttributes: newAtt)
        
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return newImage!
    }
    
}
